#coding=utf-8
from uliweb import expose

#可以省略直接引用
from uliweb import request, error, redirect
import simplejson
from sqlalchemy import desc,and_

def __begin__():
    """
    用户验证
    """
    from uliweb import functions
    return functions.require_login()


@expose('/devicespost')
class PostData(object):

    def __init__(self):
        from uliweb.orm import get_model
        self.hardwarestatusmodel = get_model('hardwarestatus')
        self.hardwaremodel = get_model('hardware')
        self.hardwaretypemodel = get_model('hardwaretype')
        self.servermodel = get_model('server')        
        self.switchmodel = get_model('switch')
        self.hardwarewarrantymodel = get_model('hardwarewarranty')
        self.rackspacemodel = get_model('rackspace')
        self.computerroommodel = get_model('computerroom')
        self.osmodel = get_model('operatingsystem')
        self.serversystemmodel = get_model('serversystem')
        self.opersgroupprojectmodel = get_model('opersgroupproject')
        self.hardwaremanufacturermodel = get_model('hardwaremanufacturer')
        
        
    def hardwarestatus(self):
        """
        返回给jquery easyui的datagride
        
        所有状态的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type   
        
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)
            
        data = {}
        data['total'] = self.hardwarestatusmodel.all().count()
        data['rows'] = []
        

        data_info = {'data':self.hardwarestatusmodel.all().order_by(order_by).limit(pageSize).offset(content)}

        for i in data_info['data']:
            
            if i.hardwarestatus_type == '' or i.hardwarestatus_type == 0:
                hardwarestatus_type = '关机'
            else:
                hardwarestatus_type = '开机'
            
            data['rows'].append({"id":i.id,
                                 "hardwarestatus_name":i.hardwarestatus_name,
                                 "hardwarestatus_type":hardwarestatus_type,
                                 "comment":i.comment
                             })
        #返回json串
        return json(data)
    
    def hardwaretype(self):
        """
        返回给jquery easyui的datagride
        
        所有硬件类型的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type        
        
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)
            
        data = {}
        data['total'] = self.hardwaretypemodel.all().count()
        data['rows'] = []
        

        data_info = {'data':self.hardwaretypemodel.all().order_by(order_by).limit(pageSize).offset(content)}

        for i in data_info['data']:
            
            if i.hardware_isport == 0:
                hardware_isport = "否"
            else:
                hardware_isport = "是"
            
            data['rows'].append({"id":i.id,
                                 "hardwaretype_name":i.hardwaretype_name,
                                 "hardware_isport":hardware_isport,
                                 "comment":i.comment
                             })
        #返回json串
        return json(data)    

    def hardwarewarranty(self):
        """
        返回给jquery easyui的datagride
        
        所有保修状态的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type   
        
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)
            
        data = {}
        data['total'] = self.hardwarewarrantymodel.all().count()
        data['rows'] = []
        

        data_info = {'data':self.hardwarewarrantymodel.all().order_by(order_by).limit(pageSize).offset(content)}

        for i in data_info['data']:
            
            data['rows'].append({"id":i.id,
                                 "hardwarewarranty_name":i.hardwarewarranty_name,
                                 "comment":i.comment
                             })
        #返回json串
        return json(data)    
    
    def hardwaremanufacturer(self):
        """
        返回给jquery easyui的datagride
        
        所有设备品牌的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type   
        
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)
            
        data = {}
        data['total'] = self.hardwaremanufacturermodel.all().count()
        data['rows'] = []
        

        data_info = {'data':self.hardwaremanufacturermodel.all().order_by(order_by).limit(pageSize).offset(content)}

        for i in data_info['data']:
                        
            data['rows'].append({"id":i.id,
                                 "hardwaremanufacturer_name":i.hardwaremanufacturer_name
                             })
        #返回json串
        return json(data)    
    
    def hardware(self):
        """
        返回给jquery easyui的datagride

        所有品牌设备的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type

        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)

        data = {}
        data['total'] = self.hardwaremodel.all().count()
        data['rows'] = []

        #data_info = {'data':self.hardwaremodel.all().order_by(self.hardwaremodel.c.id).limit(pageSize).offset(content)}
        data_info = {'data':self.hardwaremodel.all().order_by(order_by).limit(pageSize).offset(content)}

        for i in data_info['data']:

            data['rows'].append({"id":i.id,
                                 "hardware_manufacturer":i.hardwaremanufacturer_id.hardwaremanufacturer_name,
                                 "hardware_name":i.hardware_name,
                                 "hardwaretype_id":i.hardwaretype_id.hardwaretype_name,
                                 "hardware_port_num":i.hardware_port_num,
                                 "comment":i.comment
                                 })
        #返回json串
        return json(data)     
    
    def server(self):
        """
        返回给jquery easyui的datagride

        所有设备的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))

        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type 
        
        #点击树形机房菜单触发
        pid = request.GET.get('pid')        
        
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)

        data = {}
        data['rows'] = []

        
        if pid == None or pid == "99999999":
            if request.user.is_superuser:
                data['total'] = self.servermodel.all().count()
                data_info = {'data':self.servermodel.all().order_by(order_by).limit(pageSize).offset(content)}
            else:
                #非管理员只能得到该用户所在项目的设备
                data['total'] = self.servermodel.filter(self.serversystemmodel.c.server_id ==self.servermodel.c.id
                                                        ).filter(
                                                            self.serversystemmodel.c.opersgroupproject_id == self.opersgroupprojectmodel.c.id
                                                                 ).filter(
                                                                     and_(
                                                                         str(request.user) + " in (opersgroupproject.ogproject_user, \
                                                                         opersgroupproject.ogproject_opuser)")
                                                                     ).count()
                data_info = {'data':self.servermodel.filter(self.serversystemmodel.c.server_id ==self.servermodel.c.id
                                                        ).filter(
                                                            self.serversystemmodel.c.opersgroupproject_id == self.opersgroupprojectmodel.c.id
                                                                 ).filter(
                                                                     and_(
                                                                         str(request.user) + " in (opersgroupproject.ogproject_user, \
                                                                         opersgroupproject.ogproject_opuser)")
                                                                     ).order_by(order_by).limit(pageSize).offset(content)}                
                
        else:
            #print "pid===>",pid
            #functions.set_echo(True)
            if request.user.is_superuser:
                data['total'] = self.servermodel.filter(self.rackspacemodel.c.computerroom_id == int(pid)
                                                        ).filter(
                                                            self.servermodel.c.rackspace_id == self.rackspacemodel.c.id
                                                                 ).count()
                
                data_info = {'data':self.servermodel.filter(self.rackspacemodel.c.computerroom_id == int(pid)
                                                            ).filter(
                                                                self.servermodel.c.rackspace_id == self.rackspacemodel.c.id
                                                                 ).order_by(order_by).limit(pageSize).offset(content)
                             }
            
            else:
                data['total'] = self.servermodel.filter(self.rackspacemodel.c.computerroom_id == int(pid)
                                                        ).filter(
                                                            self.servermodel.c.rackspace_id == self.rackspacemodel.c.id
                                                                 ).filter(self.serversystemmodel.c.server_id ==self.servermodel.c.id
                                                        ).filter(
                                                            self.serversystemmodel.c.opersgroupproject_id == self.opersgroupprojectmodel.c.id
                                                                 ).filter(
                                                                     and_(
                                                                         str(request.user) + " in (opersgroupproject.ogproject_user, \
                                                                         opersgroupproject.ogproject_opuser)")
                                                                     ).count()
                data_info = {'data':self.servermodel.filter(self.rackspacemodel.c.computerroom_id == int(pid)
                                                            ).filter(
                                                                self.servermodel.c.rackspace_id == self.rackspacemodel.c.id
                                                                 ).filter(self.serversystemmodel.c.server_id ==self.servermodel.c.id
                                                        ).filter(
                                                            self.serversystemmodel.c.opersgroupproject_id == self.opersgroupprojectmodel.c.id
                                                                 ).filter(
                                                                     and_(
                                                                         str(request.user) + " in (opersgroupproject.ogproject_user, \
                                                                         opersgroupproject.ogproject_opuser)")
                                                                     ).order_by(order_by).limit(pageSize).offset(content)
                             }
            

        for i in data_info['data']:

            ormdata_system = functions.get_object(self.serversystemmodel, i.id, cache=True, use_local=True)

            if ormdata_system.department_id == None:
                department_name = ''
            else:
                department_name = ormdata_system.department_id.department_name
                
            if ormdata_system.opersgroup_id == None:
                opersgroup_name = ''
            else:
                opersgroup_name = ormdata_system.opersgroup_id.opersgroup_name
    
            if ormdata_system.opersgroupproject_id == None:
                opersgroupproject_name = ''
            else:
                opersgroupproject_name = ormdata_system.opersgroupproject_id.ogproject_name
                
            if ormdata_system.applicationtype_id == None:
                applicationtype_name = ''
            else:
                applicationtype_name = ormdata_system.applicationtype_id.applicationtype_name
                
            data['rows'].append({"id":i.id,
                                 "computerroom_id":i.rackspace_id.computerroom_id.cr_name,
                                 "rackspace_id":i.rackspace_id.rackspace_name,
                                 "server_manufacturer":i.hardware_id.hardwaremanufacturer_id.hardwaremanufacturer_name,
                                 "server_type":i.hardware_id.hardware_name,
                                 "server_sn":i.server_sn,
                                 "server_asset_tag":i.server_asset_tag,
                                 "hardwarestatus_id":i.hardwarestatus_id.hardwarestatus_name,
                                 "department_name":department_name,
                                 "opersgroupproject_name":opersgroupproject_name,
                                 "applicationtype_name":applicationtype_name
                                 })
        #返回json串
        return json(data)

    def switch(self):
        """
        返回给jquery easyui的datagride

        所有网络设备的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type 
        
        cr_name = request.POST.get('cr_name')
        
        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)

        data = {}
        data['rows'] = []
        
        if cr_name == None or cr_name == "":
            data['total'] = self.switchmodel.all().count()
            data_info = {'data':self.switchmodel.all().order_by(order_by).limit(pageSize).offset(content)}
        else:
            #functions.set_echo(True)
            data['total'] = self.switchmodel.filter(self.computerroommodel.c.cr_name.like('%%' + cr_name + '%%')
                                                    ).filter(self.computerroommodel.c.id == self.switchmodel.c.computerroom_id
                                                             ).count()
            data_info = {'data':self.switchmodel.filter(self.computerroommodel.c.cr_name.like('%%' + cr_name + '%%')
                                                    ).filter(self.computerroommodel.c.id == self.switchmodel.c.computerroom_id
                                                             ).order_by(order_by
                                                                        ).limit(pageSize).offset(content)}
            
        for i in data_info['data']:

            #后增字段需要判断空
            if i.hardwarestatus_id == None:
                hardwarestatus_id = ""
            else:
                hardwarestatus_id = i.hardwarestatus_id.hardwarestatus_name
                
            #后增字段需要判断空
            if i.rackspace_id == None:
                rackspace_id = ""
            else:
                rackspace_id = i.rackspace_id.rackspace_name
            data['rows'].append({"id":i.id,
                                 "switch_manufacturer":i.hardware_id.hardwaremanufacturer_id.hardwaremanufacturer_name,
                                 "computerroom_id":i.computerroom_id.cr_name,
                                 "switch_type":i.hardware_id.hardware_name,
                                 "switch_aliasname":i.switch_aliasname,
                                 "switch_port_allnum":i.hardware_id.hardware_port_num,
                                 "switch_asset_tag":i.switch_asset_tag,
                                 "switch_sn":i.switch_sn,
                                 "hardwarestatus_id":hardwarestatus_id,
                                 "rackspace_id":rackspace_id,
                                 "comment":i.comment
                                 })
        #返回json串
        return json(data)
    
    def operatingsystem(self):
        """
        返回给jquery easyui的datagride

        所有操作系统的数据
        """
        pageIndex= int(request.POST.get('page',0))
        pageSize = int(request.POST.get('rows',20))
        #排序使用
        order_by_type = request.POST.get('order','asc')
        order_by_sort = request.POST.get('sort','id')
        order_by = order_by_sort + ' ' + order_by_type

        if pageIndex == 0:
            pageIndex = 1
            content = 0
        else:
            content = pageSize * (pageIndex - 1)

        data = {}
        data['total'] = self.osmodel.all().count()
        data['rows'] = []

        #data_info = {'data':self.hardwaremodel.all().order_by(self.hardwaremodel.c.id).limit(pageSize).offset(content)}
        data_info = {'data':self.osmodel.all().order_by(order_by).limit(pageSize).offset(content)}

        for i in data_info['data']:

            data['rows'].append({"id":i.id,
                                 "os_name":i.os_name,
                                 "os_version":i.os_version,
                                 "os_arch":i.os_arch
                                 })
        #返回json串
        return json(data)          
        
###############################################################################################
    
    def hardwarestatusinfo(self):
        """
        获取硬件状态名称，提供给combobox
        """
            
        data = []
        data_info = {'data':self.hardwarestatusmodel.all().order_by(self.hardwarestatusmodel.c.id)}
        
        for i in data_info['data']:
                
            data.append({"id":i.id,
                         "hardwarestatus_name":i.hardwarestatus_name
                        })

        #返回json串
        return json(data)

    def hardwaretypeinfo(self):
        """
        获取硬件类型名称，提供给combobox
        """
            
        data = []
        data_info = {'data':self.hardwaretypemodel.all().order_by(self.hardwaretypemodel.c.id)}
        
        for i in data_info['data']:
                
            data.append({"id":i.id,
                         "hardwaretype_name":i.hardwaretype_name
                        })

        #返回json串
        return json(data) 

    def hardwarewarrantyinfo(self):
        """
        获取硬件保修状态名称，提供给combobox
        """
            
        data = []
        data_info = {'data':self.hardwarewarrantymodel.all().order_by(self.hardwarewarrantymodel.c.id)}
        
        for i in data_info['data']:
                
            data.append({"id":i.id,
                         "hardwarewarranty_name":i.hardwarewarranty_name
                        })

        #返回json串
        return json(data)

    
    #def switch_manufacturerinfo(self):
        #"""
        #获取交换机硬件品牌，提供给combobox,用于编辑展示
        #"""
            
        #data = []
        ##distinct 去除重复，mysql只对单字段进行去重，如果是查询多个字段，那么必须需要使用group by 去重字段
        #data_info = {'data':self.switchmodel.filter().fields('hardware_id').distinct().fields('hardware_id').group_by(self.switchmodel.c.hardware_id)}
        
        #for i in data_info['data']:
                
            #data.append({"id":i.hardware_id,
                         #"hardware_manufacturer":i.hardware_id.hardware_manufacturer
                        #})

        ##返回json串
        #return json(data)    
    
    def hardwareinfo(self):
        """
        获取硬件名称，提供给combobox
        """
        _id = request.GET.get("id")
            
        data = []
        
        data_info = {'data':self.hardwaremodel.filter(self.hardwaremodel.c.hardwaremanufacturer_id == _id)}
        
        for i in data_info['data']:
                
            data.append({"id":i.id,
                         "hardware_name":i.hardware_name
                        })

        #返回json串
        return json(data)
    
    def switchinfo(self):
        """
        获取交换机名称，提供给combobox
        参数:
            id:机房ID
        """
        
        _id = request.GET.get("id")
            
        data = []
        data_info = {'data':self.switchmodel.filter(self.switchmodel.c.computerroom_id == _id)}
        
        for i in data_info['data']:
                
            data.append({"id":i.id,
                         "switch_aliasname":i.switch_aliasname
                        })

        #返回json串
        return json(data) 
        
    def hardwaretype_isport(self):
        """
        返回设备类型是否包含端口设置
        """
        _id= request.POST.get('hardwaretype_id')

        ormdata = functions.get_object(self.hardwaretypemodel, _id, cache=True, use_local=True)

        return json({"status":200,"isport":ormdata.hardware_isport})    
    
    
    def operatingsysteminfo(self):
        """
        获取操作系统名称+版本+arch，提供给combobox

        """
            
        data = []
        data_info = {'data':self.osmodel.all().order_by(self.osmodel.c.os_name)}
        
        for i in data_info['data']:
                
            data.append({"id":i.id,
                         "os_info":i.os_name + "_" + i.os_version + "_" + i.os_arch
                        })

        #返回json串
        return json(data)     
    
    def hardwaremanufacturerinfo(self):
        """
        获取硬件品牌名称，提供给combobox

        """
            
        data = []
        data_info = {'data':self.hardwaremanufacturermodel.all()}
        
        for i in data_info['data']:
                
            data.append({"id":i.id,
                         "hardwaremanufacturer_name":i.hardwaremanufacturer_name
                        })

        #返回json串
        return json(data) 